package au.org.ala.collectors

class PersonController {

    static scaffold = Person

    def alphaList = {
        params.sort = 'familyName'
        def model = []
        if (params.starts) {
            params.starts.each {
                model.addAll Person.findAllByFamilyNameLike(it.toUpperCase() + "%", params)
            }
        } else {
            model = Person.list(params)
        }
        [personInstanceList: model, personInstanceTotal: model.size()]
    }

    def biog = {
        def instance = Person.get(params.id)
        if (!instance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'person.label', default: 'Person'), params.id])}"
            redirect(action: "list")
        }
        else {
            [instance: instance]
        }
    }

    def namedBiog = {
        def name = params.fname
        if (name.size() > 10 && name[-10..-1] == '.biography') {
            name = name[0..-11]
        }
        if (name.indexOf('-') > 0) {
            name = name[0..name.indexOf('-')-1]
        }
        name = name.toUpperCase()
        def pList = Person.findAllByFamilyName(name)
        def p = null

        switch (pList.size()) {
            case 0:
                // try for the whole name
                p = Person.findByFamilyName(params.fname.toUpperCase())
                break
            case 1:
                p = pList[0]
                break
            default:
                // use the first if no more intelligence
                p = pList[0]
                // more than 1 family name match - try the first name
                def namesList = params.fname.tokenize('-')
                if (namesList.size() > 1) {
                    def names = namesList[1..-1].join(' ')
                    pList.each {
                        if (it.foreNames.toLowerCase() =~ names.toLowerCase()) {
                            p = it
                        }
                    }
                }
                break
        }

        if (p) {
            forward (action: 'biog', id: p.id)
        } else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'person.label', default: 'Person'), name])}"
            redirect(action: "list")
        }

    }

}
